import { useEffect, useRef, useState } from 'react'
import { PauseCircleOutlined, PlayCircleOutlined } from '@ant-design/icons'
import { Tooltip } from 'antd'
import { useGlobalContext } from '@/contexts/GlobalContext'
import { LOOP_TIME_SECOND } from '@/config/env'

const LoopToggle: React.FC = () => {
  const { isLoop, setIsLoop } = useGlobalContext()
  const [countTime, setCountTime] = useState(LOOP_TIME_SECOND)
  const timer = useRef<NodeJS.Timeout | null>(null)
  useEffect(() => {
    if (isLoop) {
      timer.current = setInterval(() => {
        setCountTime(prevCount => {
          console.log('prevCount', prevCount)
          return prevCount > 1 ? prevCount - 1 : LOOP_TIME_SECOND
        })
      }, 1000)
    } else {
      timer.current && clearInterval(timer.current)
    }
  }, [isLoop])

  useEffect(() => {
    if (countTime <= 0) {
      timer.current && clearInterval(timer.current)
      return
    }
  }, [countTime])
  function onSwitchLoop() {
    if (isLoop) {
      setCountTime(LOOP_TIME_SECOND)
    }
    setIsLoop(!isLoop)
  }
  return (
    <Tooltip
      title={isLoop ? '关闭轮询' : '开启轮询'}
      className="cursor-pointer"
    >
      <div onClick={onSwitchLoop} className="flex flex-col items-center">
        <div className="transition-transform duration-300 ease-in-out hover:scale-125 active:scale-125 text-[18px] font-bold dark:text-[#08c]">
          {isLoop ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
        </div>
        {isLoop && <span className='text-[12px]'>{countTime}s</span>}
      </div>
    </Tooltip>
  )
}
export default LoopToggle
